﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Security;
using System.Text;
using Org.BouncyCastle.Crypto.IO;

// See https://aka.ms/new-console-template for more information

// byte[] msg = Encoding.Default.GetBytes("SM3Test");
// byte[] md = new byte[32];

// SM3Digest sm3 = new SM3Digest();
// sm3.BlockUpdate(msg, 0, msg.Length);
// sm3.DoFinal(md, 0);
// string pass = new UTF8Encoding().GetString(Hex.Encode(md));
// Console.WriteLine(pass);

byte[] plain = Encoding.Default.GetBytes("18188888888");
byte[] key = Hex.Decode("636f6d2e686e75702e6f736d702e7373");
byte[] iv = Hex.Decode("6f6e2e63727970746f2e736d2e736d34");

KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", key);
ParametersWithIV para = new ParametersWithIV(keyParam, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7PADDING");
inCipher.Init(true, para);
MemoryStream bOut = new MemoryStream();
CipherStream cOut = new CipherStream(bOut, null, inCipher);
try
{
    cOut.Write(plain, 0, plain.Length);
    cOut.Close();
}
catch (IOException e)
{
    throw e;
}
// Hex.ToHexString(bOut.ToArray());
var sm4text = Base64.ToBase64String(bOut.ToArray());
Console.WriteLine(sm4text);


IBufferedCipher outCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7PADDING");
outCipher.Init(false, para);
MemoryStream bIn = new MemoryStream(Base64.Decode(sm4text), false);
CipherStream cIn = new CipherStream(bIn, outCipher, null);
MemoryStream dout = new MemoryStream();
try
{
    int a;
    while ((a = cIn.ReadByte()) > -1)
    {
        dout.WriteByte((byte)a);
    }
}
catch (Exception e)
{
    throw e;
}
Console.WriteLine(Encoding.Default.GetString(dout.ToArray()));

